package com.java.cg.pay.controller;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.java.cg.pay.service.PayService;
import com.java.common.constants.MQConstants;
import com.java.common.utils.R;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_5
 */
@RestController
@RequestMapping("/weixin/pay")
public class PayController {
	@Autowired
	private PayService payService;
	@Autowired
	private RabbitTemplate rabbitTemplate;


	/**
	 * 创建二维码连接地址返回给前端生成二维码图片
	 */
	@RequestMapping("/create/native")
	public R createNative(String out_trade_no, String total_fee, String routingKey, String username) {
		Map<String, String> resultMap = payService.createNative(out_trade_no, total_fee, routingKey, username);
		return R.ok(resultMap);
	}

	/**
	 * 根据交易订单号 来查询订单的状态
	 */
	@RequestMapping("/status/query")
	public R queryStatus(String out_trade_no) {
		Map<String, String> resultMap = payService.queryStatus(out_trade_no);
		return R.ok(resultMap);
	}

	/**
	 * 微信支付回调(以流的形式传递过来)
	 */
	@RequestMapping("/notify/url")
	public String notifyResult(HttpServletRequest request) {
		try {
			//1.获取流信息
			ServletInputStream ins = request.getInputStream();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			while ((len = ins.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			bos.close();
			ins.close();

			//2.转换成XML字符串
			byte[] bytes = bos.toByteArray();
			//微信支付系统传递过来的XML的字符串
			String resultStrXML = new String(bytes, "utf-8");

			//3.转成MAP
			Map<String, String> map = WXPayUtil.xmlToMap(resultStrXML);
			String attachStr = map.get("attach");
			Map<String ,String> attach = JSON.parseObject(attachStr, Map.class);

			//4.发送消息给Rabbitmq
			//普通订单routingKey:pay.success 秒杀订单routingKey:seckillpay.success
			rabbitTemplate.convertAndSend(MQConstants.ORDER_EXCHANGE, attach.get("routingKey"), map);
//			rabbitTemplate.convertAndSend(MQConstants.ORDER_EXCHANGE, MQConstants.PAY_SUCCESS_ROUTING_KEY, map);

			//5.返回微信的接收请况(XML的字符串)
			Map<String, String> resultMap = new HashMap<>();
			resultMap.put("return_code", "SUCCESS");
			resultMap.put("return_msg", "OK");
			return WXPayUtil.mapToXml(resultMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
